import { CustomComponent } from '/engine/index';
import { uploadChatFile } from '../../services/chat';
import { formatFileSize } from '../../utils/index';

// 引入同声传译插件
var plugin = requirePlugin('WechatSI');
const manager = plugin.getRecordRecognitionManager();

let pressTimer = null; // 判断是否长按
let isLongPress = false;

CustomComponent({
  data: {
    isInputFocus: false,
    isVideoInput: false,
    isRecording: false,
    isCancelRecord: false, // 是否取消发送
    inputText: '',
    textAreaHeight: 50,
    bottom: 20,
    keyboardHeight: 0,
  },
  lifetimes: {
    attached() {
      this.initRecognizeListener();
      wx.onKeyboardHeightChange(res => {
        this.setData({
          keyboardHeight: res.height,
          bottom: res.height > 0 ? 0 : this.data.bottom,
        });
      });
    },
  },
  methods: {
    onTextInputChange(e) {
      this.setData({ inputText: e.detail.value });
    },
    onFocus() {
      this.setData({ isInputFocus: true });
    },
    onBlur() {
      this.setData({
        isInputFocus: false,
        keyboardHeight: 0,
      });
    },
    onClickMore() {
      this.setData({ bottom: this.data.bottom === 20 ? 200 : 20 });
      this.triggerEvent('onOpenMore', this.data.bottom);
    },
    onClickVideo() {
      this.setData({
        isVideoInput: !this.data.isVideoInput,
        isRecording: false,
        isCancelRecord: false,
        bottom: this.data.bottom === 200 ? 200 : 20,
      });
    },
    onClickSendMsg() {
      this.triggerEvent('onSendTextMsg', this.data.inputText);
      this.setData({ inputText: '' });
    },
    initRecognizeListener() {
      manager.onStop = res => {
        if (res.result && !this.data.isCancelRecord) {
          this.triggerEvent('onSendTextMsg', res.result);
        }

        this.setData({
          isRecording: false,
        });
      };
      manager.onError = () => {
        this.setData({ isRecording: false });
      };
    },
    onPressStart() {
      this.setData({ isCancelRecord: false });

      pressTimer = setTimeout(() => {
        isLongPress = true;
        this.onRealPressStart(); // 真正开始录音
      }, 100);
    },
    async onRealPressStart() {
      try {
        this.setData({ isRecording: true });
        manager.start({
          lang: 'zh_CN',
          duration: 60000,
        });
      } catch (_) {
        this.setData({ isRecording: false });
        wx.showToast({ title: '录音准备失败', icon: 'none' });
      }
    },
    onPressEnd() {
      clearTimeout(pressTimer);
      pressTimer = null;

      if (!isLongPress) {
        isLongPress = false;
        return;
      }

      isLongPress = false;
      this.setData({ isRecording: false });

      if (this.data.isCancelRecord) {
        manager.cancel(); // 取消识别
        wx.showToast({ title: '已取消', icon: 'none' });
      } else {
        manager.stop(); // 正常停止并触发 onStop 回调
      }

      this.setData({ isCancelRecord: false });
    },
    onPressMove(e) {
      const query = wx.createSelectorQuery().in(this);
      query
        .select('.press-tip')
        .boundingClientRect(rect => {
          if (rect) {
            const touch = e.touches[0];
            const isOut =
              touch.clientY < rect.top - 50 || touch.clientY > rect.bottom + 50;

            this.setData({ isCancelRecord: isOut });
          }
        })
        .exec();
    },
    onPressCancel() {
      this.onPressEnd();
    },
    // 拍照
    onTakePhoto() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'], // 可选压缩图
        sourceType: ['camera'],
        success: async res => {
          const tempFilePaths = res.tempFilePaths;
          const result = await uploadChatFile(tempFilePaths?.[0]);
          this.triggerEvent('onSendFile', { file: result?.data, type: 'img' });
          this.setData({ bottom: 20 });
        },
      });
    },
    // 从相册选择图片
    onChooseFromAlbum() {
      wx.chooseImage({
        count: 1, // 最多选 1 张
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: async res => {
          wx.showToast({
            title: '正在上传，请稍等',
            icon: 'none',
          });
          const tempFilePaths = res.tempFilePaths;
          const result = await uploadChatFile(tempFilePaths?.[0]);
          this.triggerEvent('onSendFile', {
            file: result?.data?.url,
            fileSession: result?.data?.ext1,
            ossId: result?.data?.ossId,
            type: 'img',
          });
          this.setData({ bottom: 20 });
        },
      });
    },
    // 选择附件（如文档）
    onChooseFile() {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success: async res => {
          // 过滤出 PDF 和图片格式
          const filteredFiles = res.tempFiles.filter(file => {
            const name = file.name.toLowerCase();
            const ext = name.slice(name.lastIndexOf('.'));
            return /\.(pdf|png|jpe?g)$/.test(ext);
          });

          if (filteredFiles.length === 0) {
            wx.showToast({
              title: '仅支持 PDF 或图片文件',
              icon: 'none',
            });
            return;
          }

          wx.showToast({
            title: '正在上传，请稍等',
            icon: 'none',
          });
          const tempFiles = res.tempFiles;
          const result = await uploadChatFile(
            tempFiles?.[0]?.path,
            tempFiles?.[0]?.name
          );
          this.triggerEvent('onSendFile', {
            file: result?.data?.url,
            fileSession: result?.data?.ext1,
            ossId: result?.data?.ossId,
            type: 'file',
            name: tempFiles?.[0]?.name,
            size: formatFileSize(tempFiles?.[0]?.size),
            isPdf: tempFiles?.[0]?.name?.endsWith('pdf'),
          });
          this.setData({ bottom: 20 });
        },
      });
    },
  },
});
